package com.example.jk.middlewares;

import java.io.IOException;

import com.example.jk.core.Context;
import com.example.jk.core.Middleware;
import com.example.jk.core.Next;
import com.fasterxml.jackson.databind.ObjectMapper;

import io.undertow.server.HttpHandler;
import io.undertow.util.Headers;

public class JsonMiddleware implements Middleware {

	@Override
	public void handle(Context context,Next next) {
		
		if (context.data == null) {
			return;
		}
		HttpHandler nextHandler = exchange -> {
			// 在此处添加生成和返回 JSON 的逻辑
			ObjectMapper objectMapper = new ObjectMapper();
			try {
				String json = objectMapper.writeValueAsString(context.data);
				exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");
				exchange.getResponseSender().send(json);
			} catch (IOException e) {
				e.printStackTrace();
			}
		};
		next.handle(context);
//		try {
//			next.handleRequest(((HttpServerContext) context).exchange);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
		
		
		// 这里不再尝试调用不存在的 handleExchange 方法
//		next.handleExchange(ee);

//           koa.handleRequest(context);

	}
}